package com.kgcx.order.rabbitmq;

import com.kgcx.common.client.schedule.pojo.ScheduleRecord;
import com.kgcx.common.eum.OrderEnum;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.order.domain.Order;
import com.kgcx.order.entity.OrderChangeMessage;
import com.kgcx.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * Created by zhulong on 17/11/13.
 * 运力检查失败监听
 */
@Component

public class TransportCapacityCheckFailListener {
    private static final Logger LOG = LoggerFactory.getLogger(TransportCapacityCheckFailListener.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderService service;

    @RabbitListener(queues = "kgcxOrderTransportCapacityCheckFailQueue", errorHandler = "custRabbitListenerErrorHandler")
    public void processOrderStatus(String json) {
        LOG.info("订单 - 运力检查结果：不足，json=" + json);
        //获取并解析消息
        ScheduleRecord scheduleRecord = JsonUtil.toObject(json, ScheduleRecord.class);
        try
        {
            //修改订单状态为运力数不足派车失败
            stringRedisTemplate.opsForHash().put(OrderEnum.ORDERS_STATUS, scheduleRecord.getOrder_no(), String.valueOf(OrderEnum.PLAN_FAIL));
            Order order = service.getIngOrderByOrderNo(scheduleRecord.getOrder_no());
            //修改订单实体状态
            if (order != null && scheduleRecord != null) {
                LOG.info("检查运力失败 - 取消订单并持久化，json=" + json);
                    //修改订单状态为预约失败
                    order.setOrderState(OrderEnum.PLAN_FAIL);
                    service.cancelOrderPersistence(order);
                   //qtt发给用户端结果
                    OrderChangeMessage mqMsg = new OrderChangeMessage(order.getOrderNo(), OrderEnum.PLAN_FAIL, OrderChangeMessage.MESSAGE_TYPE_DISPATCH_FAIL, "", order.getPlacingUserId());
                    service.sendMqtt(JsonUtil.toString(mqMsg)
                            , OrderEnum.ORDER_STATE_TOPIC + "." + order.getPlacingUserId());
                }

        }
        catch (Exception ex) {
            LOG.error("检查运力失败，异常，ex=" + ex.getMessage() + "，orderJson : " + json);
        }
    }
}